package com.zt.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zt.dto.PageGoods;
import com.zt.pojo.Goods;
import com.zt.service.GoodsService;
import com.zt.utils.common.dtos.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.management.Query;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 王佳祥
 * @Date: 2024 09 04 10:52
 */
@RestController
@RequestMapping("/goods")
@Slf4j
@Api(tags = "goods",description = "对controller的描述")
public class GoodsController {

    @Autowired
    private GoodsService service;

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @ApiOperation("添加商品并进行审核")
    @PostMapping("/save")
    public ResponseResult save(@ApiParam("goods 参数") @RequestBody Goods goods){
        ResponseResult responseResult = service.saveAndAuto(goods);
        return responseResult;
    }

    @SneakyThrows
    @PostMapping("/search")
    @ApiOperation("使用es进行查询")
    public ResponseResult esSearch(@RequestBody  PageGoods pageGoods){
        SearchRequest searchRequest=new SearchRequest("goods");

        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.matchQuery("name", pageGoods.getName()).fuzziness(Fuzziness.AUTO));

        searchRequest.source(searchSourceBuilder);

        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits hits = search.getHits();
        List<Goods> list=new ArrayList<>();

        for (SearchHit hit : hits) {
            System.err.println(hit.getSourceAsString());
            Goods goods = JSON.parseObject(hit.getSourceAsString(), Goods.class);
            list.add(goods);
        }
      return   ResponseResult.okResult(list);
    }

    /**
     * 分页+模糊查询
     * @param pageGoods
     * @return
     */
    @PostMapping("/page")
    public ResponseResult list(@RequestBody PageGoods pageGoods){
        Page<Goods> page = service.page(new Page<Goods>(pageGoods.getNum(),pageGoods.getSize()));
        return ResponseResult.okResult(page);
    }




    /**
     * 初始化es索引
     */
    @SneakyThrows
    @PostMapping("/esInit")
    public ResponseResult init(){
        //        查询出所有商品
        List<Goods> list = service.list();

        BulkRequest bulkRequest=new BulkRequest("goods");

//        遍历商品
        for (Goods goods : list) {
//            创建索引
            IndexRequest indexRequest=new IndexRequest("goods")
//                    指定id
                    .id(goods.getId()+"")

//                    数据类型
                    .source(JSON.toJSONString(goods),XContentType.JSON);

//            使用bulk添加
            bulkRequest.add(indexRequest);


        }
        restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);

        return ResponseResult.okResult("导入成功"+list.size());
    }

    /**
     * 修改商品名称
     * @param goods
     * @return
     */
    @PostMapping("/updateGoods")
    public ResponseResult updateGoods(@RequestBody Goods goods){
        ResponseResult responseResult = service.updateGoods(goods);
        return  responseResult;
    }

    /**
     * 修改回显
     * @param id
     * @return
     */
    @PostMapping("/updateOne/{id}")
    public ResponseResult updateOne(@PathVariable  Integer id){
        Goods byId = service.getById(id);
        return ResponseResult.okResult(byId);
    }

    /**
     * 删除商品
     * @param id
     * @return
     */
    @SneakyThrows
    @DeleteMapping("/delete/{id}")
    public ResponseResult DeleteGoods(@PathVariable Integer id){
        service.removeById(id);
//        同步es
        DeleteRequest deleteRequest=new DeleteRequest("zk3_test");
        deleteRequest.id(id+"");
        restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
        return ResponseResult.okResult("删除成功");
    }
}


